package com.example.mylibrary.util;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.io.InputStream;

/**
 * Created by fairplay on 2018/5/29.
 */

public class ResourcesUtils {
    public static final String RES_TYPE_LAYOUT = "layout";
    public static final String RES_TYPE_DRAWABLE = "drawable";
    public static final String RES_TYPE_STRING = "string";
    public static final String RES_TYPE_COLOR = "color";
    public static final String RES_TYPE_ID = "id";
    public static final String RES_TYPE_STYLE = "style";

    private ResourcesUtils() {
    }

    public static int getLayoutResId(Context context, String name) {
        return getResourceID(context, "layout", name);
    }

    public static int getDrawableResId(Context context, String name) {
        return getResourceID(context, "drawable", name);
    }

    public static int getStringResId(Context context, String name) {
        return getResourceID(context, "string", name);
    }

    public static int getColorResId(Context context, String name) {
        return getResourceID(context, "color", name);
    }

    public static int getIdResId(Context context, String name) {
        return getResourceID(context, "id", name);
    }

    public static int getStyleResId(Context context, String name) {
        return getResourceID(context, "style", name);
    }

    public static int getResourceID(Context context, String type, String name) {
        Resources resource = context.getResources();
        String pkgName = context.getPackageName();
        return resource.getIdentifier(name, type, pkgName);
    }

    public static Drawable getDrawable(int a, int r, int g, int b) {
        GradientDrawable drawable = new GradientDrawable(GradientDrawable.Orientation.LEFT_RIGHT, new int[]{0, Color.argb(a, r, g, b)});
        return drawable;
    }

    public static <T extends View> T findViewById(Context context, int resId) {
        return (T) LayoutInflater.from(context).inflate(resId, (ViewGroup)null);
    }

    public static Drawable resourceToDrawable(Context context, int resId) {
        return context.getResources().getDrawable(resId);
    }

    public static Bitmap resourceToBitmap(Context context, int resId) {
        Resources r = context.getResources();
        InputStream is = r.openRawResource(resId);
        BitmapDrawable bmpDraw = new BitmapDrawable(is);
        return bmpDraw.getBitmap();
    }
}
